package com.have.blog.sprider.controller;

import com.have.blog.sprider.pipeline.PicturePipeline;
import com.have.blog.sprider.processor.PictureProcessor;
import com.have.blog.sprider.vo.PictureSpiderVo;
import com.have.blog.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.List;

@RestController
@RequestMapping("/spider")
@Api(value = "图片RestApi", tags = {"图片爬取相关接口"})
@Slf4j
public class PictureSpiderController {
    @Autowired
    private PicturePipeline picturePieline;
    @Autowired
    private PictureProcessor pictureProcesser;

    @ApiOperation(value = "通过爬虫爬取关键词图片", notes = "通过爬虫爬取关键词图片")
    @PostMapping("/spiderPicture")
    public String spiderPicture(@RequestBody PictureSpiderVo pictureSpider) throws UnsupportedEncodingException {
        String searchUrl;
        if (pictureSpider.getCurrentPage() > 1) {
            searchUrl = "https://foter.com/search/instant/?q=" + pictureSpider.getKeyword() + "&page=" + pictureSpider.getCurrentPage();
        } else {
            searchUrl = "https://foter.com/search/instant/?q=" + pictureSpider.getKeyword();
        }
        // 获取html页面
        String html = pictureProcesser.getHtml(searchUrl);
        // 获取页面中的图片
        List<String> imageUrlList = pictureProcesser.getImageUrl(html);
        List<String> imageSrcList = pictureProcesser.getImageSrc(imageUrlList);
        return ResultUtils.successWithData(imageSrcList);
//        return ResultUtils.errorWithMessage("暂时不可用哦~");
    }
}
